
import Vue from 'vue';
import store from '../store';
import VueRouter from 'vue-router';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { Session } from '@/utils/storage';
import { PrevLoading } from '@/utils/loading.js';
import { useMenuApi } from '@/api/menu';

const menuApi = useMenuApi();

// 解决 `element ui` 导航栏重复点菜单报错问题
const originalPush = VueRouter.prototype.push;
VueRouter.prototype.push = function push(location) {
	return originalPush.call(this, location).catch((err) => err);
};

// 安装 VueRouter 插件
Vue.use(VueRouter);

// 定义动态路由
const dynamicRoutes = [
	{
		path: '/',
		name: '/',
		component: 'layout/index',
		redirect: '/dualPrevention/home',
		meta: {
			isKeepAlive: true,
		},
		children: [],
	},
];

// 定义静态路由
const staticRoutes = [
	{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login'),
		meta: {
			title: '登录',
		},
	},
	{
		path: '/leadership',
		name: 'leadership',
		component: () => import('@/views/leadership'),
		meta: {
			title: '领导驾驶舱',
		},
	},
	{
		path: '/404',
		name: 'notFound',
		component: () => import('@/views/error/404.vue'),
		meta: {
			title: 'message.staticRoutes.notFound',
		},
	},
	{
		path: '/401',
		name: 'noPower',
		component: () => import('@/views/error/401.vue'),
		meta: {
			title: 'message.staticRoutes.noPower',
		},
	},
];

// 加载静态路由
const createRouter = () =>
	new VueRouter({
		// mode: 'history',
		mode: 'hash',
		base: window.__POWERED_BY_QIANKUN__ ? '/personnelPositionShip' : '/',
		routes: staticRoutes,
	});

// 创建路由
const router = createRouter();

// 加载 loading
PrevLoading.start();

// 多级嵌套数组处理成一维数组
export function formatFlatteningRoutes(arr) {
	if (arr.length <= 0) return false;
	for (let i = 0; i < arr.length; i++) {
		if (arr[i].children) {
			arr = arr.slice(0, i + 1).concat(arr[i].children, arr.slice(i + 1));
		}
	}
	return arr;
}

// 处理 tagsViewList 数据，默认路由全部缓存
// isKeepAlive 处理 `name` 值，进行路由缓存
export function formatTwoStageRoutes(arr) {
	if (arr.length <= 0) return false;
	const newArr = [];
	const cacheList = [];
	arr.forEach((v) => {
		newArr.push({ ...v });
		cacheList.push(v.name);
		store.dispatch('keepAliveNames/setCacheKeepAlive', cacheList);
	});
	return newArr;
}

// 判断路由 meta.roles 中是否包含当前登录用户权限字段
export function hasAuth(roles, route) {
	if (route.meta && route.meta.roles) return roles.some((role) => route.meta.roles.includes(role));
	else return true;
}

// 递归过滤有权限的路由
export function setFilterMenuFun(routes, role) {
	const menu = [];
	routes.forEach((route) => {
		const item = { ...route };
		if (hasAuth(role, item)) {
			if (item.children) item.children = setFilterMenuFun(item.children, role);
			menu.push(item);
		}
	});
	return menu;
}

// 缓存多级嵌套数组处理后的一维数组(tagsView、菜单搜索中使用：未过滤隐藏的(isHide))
export function setCacheTagsViewRoutes(arr) {
	// 先处理有权限的路由，否则 tagsView、菜单搜索中无权限的路由也将显示
	let rolesRoutes = setFilterMenuFun(arr, store.state.userInfos.userInfos.roles);
	// 添加到 vuex setTagsViewRoutes 中
	store.dispatch('tagsViewRoutes/setTagsViewRoutes', formatTwoStageRoutes(formatFlatteningRoutes(rolesRoutes)));
}

// 递归处理多余的 layout : <router-view>，让需要访问的组件保持在第一层 layout 层。
// 因为 `keep-alive` 只能缓存二级路由
// 默认初始化时就执行
export function keepAliveSplice(to) {
	if (to.matched && to.matched.length > 2) {
		to.matched.map((v, k) => {
			if (v.components.default instanceof Function) {
				v.components.default().then((components) => {
					if (components.default.name === 'parent') {
						to.matched.splice(k, 1);
						router.push({ path: to.path, query: to.query });
						keepAliveSplice(to);
					}
				});
			} else {
				if (v.components.default.name === 'parent') {
					to.matched.splice(k, 1);
					keepAliveSplice(to);
				}
			}
		});
	}
}

// 处理后端返回的 `component` 路径，拼装实现懒加载
export function loadView(path) {
	// console.log(path, 'loadView')
	/**
	 * 打包成一个 js、一个 css
	 */
	if (path.indexOf('layout') > -1) return () => Promise.resolve(require(`@/${path}`));
	else return () => Promise.resolve(require(`@/views/${path}`));

	/**
	 * 打包成多个 js、多个 css
	 */
	// if (path.indexOf('layout') > -1) return () => import(`@/${path}`);
	// else return () => import(`@/views/${path}`);
}

// 递归处理每一项 `component` 中的路径
export function dynamicRouter(routes) {
	return routes.map((view) => {
		if (view.component) view.component = loadView(view.component);
		if (view.children) dynamicRouter(view.children);
		return view;
	});
}

// 重置路由
export function resetRouter() {
	router.matcher = createRouter().matcher;
}

// 延迟关闭进度条
export function delayNProgressDone(time = 300) {
	setTimeout(() => {
		NProgress.done();
	}, time);
}

// 动态加载后端返回路由路由(模拟数据)
export function getRouterList(router, to, next) {
	// console.log(Session.get('userInfo'))
	if (!Session.get('userInfo')) return false;
	addRouter(router, to, next);
	// if (Session.get('userInfo').userName === 'admin') adminUser(router, to, next);
	// else if (Session.get('userInfo').userName === 'test') testUser(router, to, next);
}

// 动态加载后端返回路由路由(模拟数据)
export function addRouter(router, to, next) {
	resetRouter();
	let data = [
		{
			path: '/home',
			name: 'home',
			component: 'home',
			meta: {
				title: 'message.router.home',
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: true,
				isIframe: false,
				roles: ['admin', 'common'],
				icon: 'iconfont icon-shouye',
			},
		},
		{
			path: '/tools',
			name: 'tools',
			component: 'tools',
			meta: {
				title: 'message.router.tools',
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: false,
				isIframe: false,
				roles: ['admin', 'common'],
				icon: 'iconfont icon-gongju',
			},
		},
		{
			path: '/menu',
			name: 'menu',
			component: 'layout/routerView/parent',
			redirect: '/menu/menu1',
			meta: {
				title: 'message.router.menu',
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: false,
				isIframe: false,
				roles: ['admin', 'common'],
				icon: 'iconfont icon-caidan',
			},
			children: [
				{
					path: '/menu/menu1',
					name: 'menu1',
					component: 'layout/routerView/parent',
					redirect: '/menu/menu1/menu11',
					meta: {
						title: 'message.router.menu1',
						isLink: '',
						isHide: false,
						isKeepAlive: true,
						isAffix: false,
						isIframe: false,
						roles: ['admin', 'common'],
						icon: 'iconfont icon-caidan',
					},
					children: [
						{
							path: '/menu/menu1/menu11',
							name: 'menu11',
							component: 'menu/menu1/menu11/index',
							meta: {
								title: 'message.router.menu11',
								isLink: '',
								isHide: false,
								isKeepAlive: true,
								isAffix: false,
								isIframe: false,
								roles: ['admin', 'common'],
								icon: 'iconfont icon-caidan',
							},
						},
						{
							path: '/menu/menu1/menu12',
							name: 'menu12',
							component: 'layout/routerView/parent',
							redirect: '/menu/menu1/menu12/menu121',
							meta: {
								title: 'message.router.menu12',
								isLink: '',
								isHide: false,
								isKeepAlive: true,
								isAffix: false,
								isIframe: false,
								roles: ['admin', 'common'],
								icon: 'iconfont icon-caidan',
							},
							children: [
								{
									path: '/menu/menu1/menu12/menu121',
									name: 'menu121',
									component: 'menu/menu1/menu12/menu121/index',
									meta: {
										title: 'message.router.menu121',
										isLink: '',
										isHide: false,
										isKeepAlive: true,
										isAffix: false,
										isIframe: false,
										roles: ['admin', 'common'],
										icon: 'iconfont icon-caidan',
									},
								},
								{
									path: '/menu/menu1/menu12/menu122',
									name: 'menu122',
									component: 'menu/menu1/menu12/menu122/index',
									meta: {
										title: 'message.router.menu122',
										isLink: '',
										isHide: false,
										isKeepAlive: true,
										isAffix: false,
										isIframe: false,
										roles: ['admin', 'common'],
										icon: 'iconfont icon-caidan',
									},
								},
							],
						},
						{
							path: '/menu/menu1/menu13',
							name: 'menu13',
							component: 'menu/menu1/menu13/index',
							meta: {
								title: 'message.router.menu13',
								isLink: '',
								isHide: false,
								isKeepAlive: true,
								isAffix: false,
								isIframe: false,
								roles: ['admin', 'common'],
								icon: 'iconfont icon-caidan',
							},
						},
					],
				},
				{
					path: '/menu/menu2',
					name: 'menu2',
					component: 'menu/menu2/index',
					meta: {
						title: 'message.router.menu2',
						isLink: '',
						isHide: false,
						isKeepAlive: true,
						isAffix: false,
						isIframe: false,
						roles: ['admin', 'common'],
						icon: 'iconfont icon-caidan',
					},
				},
			],
		},
		{
			path: '/fun',
			name: 'funIndex',
			component: 'layout/routerView/parent',
			redirect: '/fun/tagsView',
			meta: {
				title: 'message.router.funIndex',
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: false,
				isIframe: false,
				roles: ['admin', 'common'],
				icon: 'iconfont icon-crew_feature',
			},
			children: [
				{
					path: '/fun/tagsView',
					name: 'funTagsView',
					component: 'fun/tagsView/index',
					meta: {
						title: 'message.router.funTagsView',
						isLink: '',
						isHide: false,
						isKeepAlive: true,
						isAffix: false,
						isIframe: false,
						roles: ['admin', 'common'],
						icon: 'el-icon-thumb',
					},
				},
				{
					path: '/fun/signCanvas',
					name: 'funSignCanvas',
					component: 'fun/signCanvas/index',
					meta: {
						title: 'message.router.funSignCanvas',
						isLink: '',
						isHide: false,
						isKeepAlive: true,
						isAffix: false,
						isIframe: false,
						roles: ['admin', 'common'],
						icon: 'el-icon-edit',
					},
				},
			],
		},
		{
			path: '/pages',
			name: 'pagesIndex',
			component: 'layout/routerView/parent',
			redirect: '/pages/formAdapt',
			meta: {
				title: 'message.router.pagesIndex',
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: false,
				isIframe: false,
				roles: ['admin', 'common'],
				icon: 'iconfont icon-fuzhiyemian',
			},
			children: [
				{
					path: '/pages/formAdapt',
					name: 'pagesFormAdapt',
					component: 'pages/formAdapt/index',
					meta: {
						title: 'message.router.pagesFormAdapt',
						isLink: '',
						isHide: false,
						isKeepAlive: true,
						isAffix: false,
						isIframe: false,
						roles: ['admin', 'common'],
						icon: 'iconfont icon-biaodan',
					},
				},
			],
		},
		{
			path: '/personal',
			name: 'personal',
			component: 'personal/index',
			meta: {
				title: 'message.router.personal',
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: false,
				isIframe: false,
				roles: ['admin', 'common'],
				icon: 'iconfont icon-gerenzhongxin',
			},
		},
		{
			path: '/link',
			name: 'layoutLinkView',
			component: 'layout/routerView/parent',
			meta: {
				title: 'message.router.layoutLinkView',
				isLink: 'https://element-plus.gitee.io/#/zh-CN/component/installation',
				isHide: false,
				isKeepAlive: false,
				isAffix: false,
				isIframe: false,
				roles: ['admin'],
				icon: 'iconfont icon-caozuo-wailian',
			},
		},
		{
			path: '/iframes',
			name: 'layoutIfameView',
			component: 'layout/routerView/parent',
			meta: {
				title: 'message.router.layoutIfameView',
				isLink: 'https://element-plus.gitee.io/zh-CN/#/zh-CN/component/installation',
				isHide: false,
				isKeepAlive: false,
				isAffix: true,
				isIframe: true,
				roles: ['admin'],
				icon: 'iconfont icon-neiqianshujuchucun',
			},
		},
	];
	let user_id = Session.get('userInfo').id;
	// let sonid = '5715256b2f474bb5bf1679c92997f372'; // 人员定位 
	// let sonid = 'e53a57383d504d7fb07b6ee1bb8ddd35'; // tszy 
	let sonid = '788a49487e8243198d510f78a549109f'; // 双重预防 
	menuApi.getMenu({ user_id: user_id, sonid: sonid }).then(async (res) => {
		// console.log(res.info[0].children[0].children, '---------------573');
		let mentList = res.info[0].children[0].children;
		store.dispatch('userInfos/setUserInfos');
		let transformedMenuData = transformMenuToRoutes(mentList);

		// console.log(data, 'data');
		// 将转换后的菜单数据与新的路由对象合并
		// transformedMenuData = [newRouteHome].concat(transformedMenuData);

		store.dispatch('routesList/setRoutesList', setFilterMenuFun(transformedMenuData, store.state.userInfos.userInfos.roles));
		dynamicRoutes[0].children = transformedMenuData;
		const awaitRoute = await dynamicRouter(dynamicRoutes);
		[...awaitRoute, { path: '*', redirect: '/404' }].forEach((route) => {
			router.addRoute({ ...route });
		});
		setCacheTagsViewRoutes(JSON.parse(JSON.stringify(transformedMenuData)));
		next({ ...to, replace: true });
	}).catch((err) => {
		console.log(err);
	})
}
function transformMenuToRoutes(menu) {
	return menu.map(item => {
		// 提取功能按钮权限
		if (item.children && item.children.length > 0) {
			const permissions = item.children
				.filter(child => child.mtype === 'FUN') // 过滤出功能按钮
				.map(child => child.code); // 提取功能按钮的 code

			// 将权限添加到父菜单的 meta.permission 中
			if (permissions.length > 0) {
				if (!item.meta) {
					item.meta = {};
				}
				if (!item.meta.permission) {
					item.meta.permission = [];
				}
				item.meta.permission.push(...permissions);
			}

			// 移除功能按钮节点
			item.children = item.children.filter(child => child.mtype !== 'FUN');
		}

		// 基础结构
		const transformedItem = {
			path: item.path,
			name: item.title,
			component: item.children && item.children.length > 0 ? 'layout/routerView/parent' : item.code,
			redirect: item.children && item.children.length > 0 ? item.children[0].path : '',
			meta: {
				title: item.title,
				isLink: '',
				isHide: false,
				isKeepAlive: true,
				isAffix: item.title === '首页', // 仅首页固定
				isIframe: false,
				roles: Session.get('userInfo').ukey, // 初始化为默认权限
				icon: `iconfont ${item.icon}`,
				permission: item.meta?.permission || [], // 添加权限按钮
			},
		};

		// 如果有子菜单，递归处理子菜单
		if (item.children && item.children.length > 0) {
			transformedItem.children = transformMenuToRoutes(item.children);
		}

		return transformedItem;
	});
}
function transformMenuData(menuData) {
    return menuData
        .filter((item) => item.mtype === 'MENU') // 只处理 mtype 为 "MENU" 的项
        .map((item, index) => {
            const transformedItem = {
                path: item.path,
                name: item.code,
                component: item.code,
				redirect: '',
                meta: {
                    title: `${item.title}`,
                    isLink: '',
                    isHide: false,
                    isKeepAlive: true,
                    isAffix: item.title === '首页', // 修改这里,
                    isIframe: false,
                    roles: Session.get('userInfo').ukey, // 初始化为默认权限
                    icon: `iconfont ${item.icon}`,
                },
            };

            // 如果有子菜单
            if (item.children && item.children.length > 0) {
                // 递归处理子菜单
                transformedItem.children = transformMenuData(item.children);

                // 提取子菜单中的按钮权限（mtype 为 "FUN"）
                const buttonPermissions = item.children
                    .filter(child => child.mtype === 'FUN') // 过滤出按钮权限
                    .map(child => child.code); // 提取按钮权限的 code

                // 将按钮权限添加到当前菜单的 meta.roles 中
                transformedItem.meta.permission = [
                    ...buttonPermissions, // 添加按钮权限
                ];
            }

            return transformedItem;
        });
}


// 路由加载前
router.beforeEach((to, from, next) => {
	// console.log(222)
	keepAliveSplice(to);
	NProgress.configure({ showSpinner: false });
	if (to.meta.title && to.path !== '/login') NProgress.start();
	let token = Session.get('token');
	// console.log(token, 'token');
	if (window.__POWERED_BY_QIANKUN__) {
		// eslint-disable-next-line no-undef
			if (!token) {
				next({ path: '/404' });
			} else {
				// console.log('token存在');
				if (Object.keys(store.state.routesList.routesList).length <= 0) {
					getRouterList(router, to, next);
					// console.log(' 如果没有路由列表，需要获取');
				} else {
					next();
					// console.log(' 如果有路由列表，直接访问');
					delayNProgressDone(0);
				}
			}
		// console.log('qiankun环境');
	
	} else {
		// console.log('非qiankun环境');
		if (to.path === '/login' && !token) {
			// console.log('访问登录页且无token');
			NProgress.start();
			next();
			delayNProgressDone();
		} else {
			if (!token) {
				// console.log('访问登录页且无token');
				NProgress.start();
				next('/login');
				Session.clear();
				delayNProgressDone();
			} else if (token && to.path === '/login') {
				// console.log('访问登录页且有token');
				next('/home');
				delayNProgressDone();
			} else {
				if (Object.keys(store.state.routesList.routesList).length <= 0) {
					getRouterList(router, to, next);
					// console.log(' 如果没有路由列表，需要获取');
				} else {
					next();
					// console.log(' 如果有路由列表，直接访问');
					delayNProgressDone(0);
				}
			}
		}
	}
});

// 路由加载后
router.afterEach(() => {
	PrevLoading.done();
	delayNProgressDone();
});

// 导出路由
export default router;
